﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ldt.DataEngine.DataFlowParse.Model;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.EvidenceDerivation;
using LdtJudge.DataEngine.Model.EvidenceFact;
using LdtJudge.DataEngine.Model.EvidenceQuestion;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;

namespace LdtDataEngin.ModuleDetail.OptimizationModule.EvidenceDerivation
{
    /// <summary>
    /// 质证意见对要素认定状态的影响
    /// </summary>
    public class QuestionElementComparison
    {
        /// <summary>
        /// 上下文
        /// </summary>
        public DataContext dataContext { get; set; }

        /// <summary>
        /// 模块名
        /// </summary>
        public string ModuleName { get; set; }
        public QuestionElementComparison(DataContext _dataContext,string moduleName)
        {
            this.dataContext = _dataContext;
            this.ModuleName = moduleName;
        }

        public void ElementComparison() {
            List<EviFactElementRelationModel> relations = new List<EviFactElementRelationModel>();
            if (dataContext.DataLayerOpt.EviFactElementRelations != null && dataContext.DataLayerOpt.EviFactElementRelations.Any())
                relations = dataContext.DataLayerOpt.EviFactElementRelations;
            if (relations != null && relations.Any())
            {
                var groupList = relations.GroupBy(x => new { x.FactElementId, x.Xpath })
                                       .Select(x => new
                                       {
                                           FactElementId = x.Key.FactElementId,
                                           Xpath = x.Key.Xpath,
                                           EvidenceNameIds=string.Join(',', x.Select(j=>j.EvidenceNameId).ToList()),
                                           EvidenceValidSource=x.FirstOrDefault().EvidenceValidSource,
                                           EvidenceAffirmStatus=x.FirstOrDefault().EvidenceAffirmStatus
                                       }).ToList();
                if (groupList !=null && groupList.Any())
                {
                    foreach (var item in groupList)
                    {
                        //如果存在要素认定情况并且证据效力来源是法官就保留上结果集否则执行质证意见与证据认定结果
                        if ((string.IsNullOrWhiteSpace(item.EvidenceAffirmStatus)) || (!string.IsNullOrWhiteSpace(item.EvidenceAffirmStatus) && item.EvidenceValidSource != "1")) {
                            //无质证意见的证据Id
                            List<string> evidenceIds = new List<string>();
                            var oldStatus = item.EvidenceAffirmStatus;
                            var eviQuestionRelations = ConvertToEviQuestionRelationModel();
                            var evidenceNameIds = item.EvidenceNameIds?.Split(",").ToList();
                            var evQuestionJGList = eviQuestionRelations.Where(a => !string.IsNullOrEmpty(a.QuestionJG)).ToList();
                            eviQuestionRelations = eviQuestionRelations.Where(a => string.IsNullOrEmpty(a.QuestionJG)).ToList();
                            if (evQuestionJGList!=null && evQuestionJGList.Count>0)
                            {
                                foreach (var rdjg in evQuestionJGList)
                                {
                                    if (rdjg.QuestionJG=="0")
                                    {
                                        SetEvidenceAffirmStatus(relations, item.FactElementId, item.Xpath, "0");
                                    }
                                    else
                                    {
                                        SetEvidenceAffirmStatus(relations, item.FactElementId, item.Xpath, "1");
                                    }
                                }
                            }
                            else
                            {
                                foreach (var id in evidenceNameIds)
                                {
                                    //如果证据没有质证意见，将证据名称Id添加到无质证意见的证据Id集合中
                                    if (eviQuestionRelations.Any(x => x.EvidenceNameID.Contains(id)))
                                        evidenceIds.Add(id);

                                }
                                //判断是否有无质证意见的证据
                                if (evidenceIds.Any())
                                {
                                    if (oldStatus == "1" || string.IsNullOrWhiteSpace(oldStatus))
                                        SetEvidenceAffirmStatus(relations, item.FactElementId, item.Xpath, "1");
                                    else
                                        SetEvidenceAffirmStatus(relations, item.FactElementId, item.Xpath, "0");
                                }
                                else
                                {
                                    //当所有证据都有质证意见时，事实要素状态为待认定
                                    SetEvidenceAffirmStatus(relations, item.FactElementId, item.Xpath, "0");
                                }
                            }
                            
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 调整事实要素认定状态
        /// </summary>
        private void SetEvidenceAffirmStatus(List<EviFactElementRelationModel> relations,string factElementId,string xPath,string status)
        {
            foreach (var item in relations.Where(x=>x.FactElementId==factElementId && x.Xpath==xPath))
            {
                item.EvidenceAffirmStatus = status;
            }
            dataContext.DataLayerOpt.EviFactElementRelations = relations;
        }

        /// <summary>
        /// 转换证据与质证意见关系模型
        /// </summary>
        /// <param name="xmlPath"></param>
        private List<EvidenceQuestionRelationModel> ConvertToEviQuestionRelationModel()
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            List<EvidenceQuestionRelationModel> relationList = new List<EvidenceQuestionRelationModel>();
            List<DataModel> analysisResultsDataModels = dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList;
            DataModel rootDataModel = XmlUtility.ConditionFirstOrDefaultDataModel(analysisResultsDataModels,"",dataContext.DataLayerAns.StageProcessAnalysisDataModel.path);
            List<DataModel> dataModels = xmlUtilCommon.SubordinateDataModelList(analysisResultsDataModels, rootDataModel);
            DataModel relationDataModel = dataModels.FirstOrDefault(x => x.XmlPath.EndsWith("证据质证意见关系"));
            if (relationDataModel != null)
            {
                //证据质证意见关系数据节点
                List<DataModel> relationSubDataModels = xmlUtilCommon.SubordinateDataModelList(analysisResultsDataModels, relationDataModel);
                if (relationSubDataModels != null && relationSubDataModels.Any())
                {
                    foreach (var model in relationSubDataModels.Where(x=>x.ID!=relationDataModel.ID))
                    {
                        EvidenceQuestionRelationModel relation = new EvidenceQuestionRelationModel();
                        AttributeInfo attribute = model.AttributesList.Where(a => a.Name == "证据名称ID")?.First();
                        if (attribute != null)
                            relation.EvidenceNameID = attribute.sourceList.Where(a => a.IsCheck == "1")?.First().SaveValue;
                        attribute = model.AttributesList.Where(a => a.Name == "证据主张方ID")?.First();
                        if (attribute != null)
                            relation.EvidenceID = attribute.sourceList.Where(a => a.IsCheck == "1")?.First().SaveValue;
                        attribute = model.AttributesList.Where(a => a.Name == "质证方ID")?.First();
                        if (attribute != null)
                            relation.QuesetionR = attribute.sourceList.Where(a => a.IsCheck == "1")?.First().SaveValue;
                        attribute = model.AttributesList.Where(a => a.Name == "质证内容ID")?.First();
                        if (attribute != null)
                            relation.QuestionID = attribute.sourceList.Where(a => a.IsCheck == "1")?.First().SaveValue;
                        if (!string.IsNullOrEmpty(relation.QuestionID))
                        {
                            DataModel dataModel = dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList.FirstOrDefault(a => a.ID == relation.QuestionID);
                            if (dataModel!=null)
                            {
                                AttributeInfo attinfo = dataModel.AttributesList.FirstOrDefault(a => a.Name == "质证结果");
                                if (attinfo!=null)
                                {
                                    relation.QuestionJG= attinfo.sourceList.Where(a => a.IsCheck == "1")?.First().SaveValue;
                                }
                            }
                        }
                        relationList.Add(relation);
                    }
                }
            }
            return relationList;
        }

    }
}
